package logic

import (
	"class/cache"
	"class/classrpc/classrpc"
	"class/classrpc/internal/svc"
	"class/models"
	"class/pkg"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"math/rand"
)

type CaptChaLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCaptChaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptChaLogic {
	return &CaptChaLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *CaptChaLogic) CaptCha(in *classrpc.CaptChaRequest) (*classrpc.CaptChaResponse, error) {
	// todo: add your logic here and delete this line

	var user models.User
	models.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("当前账号已注册,请更换账号后重试")
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}

	user = models.User{
		Account:   in.Account,
		Password:  pkg.Md5(in.Password),
		Name:      fmt.Sprintf("用户_%d", rand.Intn(10000)),
		HeadImage: "https://ts1.tc.mm.bing.net/th/id/OIP-C.p6hdmBEvZCMwVcWDVnQr0QAAAA?w=205&h=211&c=8&rs=1&qlt=90&o=6&cb=12&dpr=1.3&pid=3.1&rm=2",
	}

	models.DB.Debug().Create(&user)

	return &classrpc.CaptChaResponse{
		UserId: int64(user.ID),
	}, nil
}
